package cn.aitrox.ry.service.image.mq.consumer;

import cn.aitrox.ry.bean.RespResult;
import cn.aitrox.ry.constant.CommonConstant;
import cn.aitrox.ry.service.image.mq.msg.ImageTransferMsg;
import cn.aitrox.ry.service.image.service.ImageTransferService;
import cn.aitrox.ry.util.JSONUtil;
import cn.aitrox.ry.util.LogUtil;
import org.apache.activemq.command.ActiveMQTextMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.jms.Message;
import javax.jms.MessageListener;

@Component
public class ImageTransferConsumer implements MessageListener {

    private static final Logger LOG = LoggerFactory.getLogger(ImageTransferConsumer.class);

    @Autowired
    private ImageTransferService imageTransferService;

    @Override
    public void onMessage(Message message) {
        String msg = CommonConstant.EMPTY;
        Integer id = null;
        long startTime = System.currentTimeMillis();
        try {
            ActiveMQTextMessage textMessage = (ActiveMQTextMessage) message;
            msg = textMessage.getText();
            LOG.info(LogUtil.gen("ImageTransferConsumer receive ----------> ", "msg", msg));
            ImageTransferMsg imageTransferMsg = JSONUtil.fromJson(msg, ImageTransferMsg.class);
            id = imageTransferMsg.getId();
            RespResult respResult = imageTransferService.handlerMsg(imageTransferMsg, startTime);
            if (respResult._isOk()) {
                LOG.info(LogUtil.gen("ImageTransferConsumer success ----------> ", "msg", msg));
            } else {
                LOG.error(LogUtil.gen("ImageTransferConsumer fail ----------> ", "err", respResult.getMsg() + "", "msg", msg));
            }
        } catch (Exception e) {
            if (null != id) {
                imageTransferService.handlerFail(id, e.getMessage(), startTime);
            }
            LOG.error(LogUtil.genException(e, "ImageTransferConsumer error ----------> ", "msg", msg), e);
        }
    }

}
